package com.shaoshaohuo.app.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Market;
import com.shaoshaohuo.app.entity.Price;
import com.shaoshaohuo.app.entity.PriceEntity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.adapter.MarketPriceAdapter;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.shaoshaohuo.app.utils.CityinfoUtil;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.util.ArrayList;
import java.util.List;

/**
 * 电商 市场行情
 * 
 * @author cao
 *
 */
public class MarketPriceFragment extends Fragment implements OnClickListener, IXListViewListener {

	public static final String ARGUMENT = "argument";
	private String mArgument;
	private View mContentView;
	private TopbarView mTopbarView;
	private TextView mShucai;
	private TextView mShuiguo;
	private TextView mQita;
	private TextView mChandi;
	private TextView mShichang;
	private XListView mListView;
	private List<Price> list = new ArrayList<>(); // 当前 行情 集合
	private MarketPriceAdapter marketPriceAdapter;// 适配器

	private int checkedId = -1; // 当前选中的 textview id

	private CascadingMenuPopWindow cascadingMenuPopWindowMarket;// 选择 城市
	private CascadingMenuPopWindow cascadingMenuPopWindowCity;// 选择 市场
	private Cityinfo marketCity; // 选中的市
	private Market selectMarket;// 选择的市场

	// 请求数据保存参数
	private String type;
	private String cursor;
	private String offset = "20";
	private String levelType;
	private String addressCode;
	private String bigName;

	public static MarketPriceFragment newInstance(String argument) {
		Bundle bundle = new Bundle();
		bundle.putString(ARGUMENT, argument);
		MarketPriceFragment contentFragment = new MarketPriceFragment();
		contentFragment.setArguments(bundle);
		return contentFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		if (bundle != null)
			mArgument = bundle.getString(ARGUMENT);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		if (mContentView == null) {
			mContentView = inflater.inflate(R.layout.fragment_market_price, null);

			initView();
			setUpView();
			requestData(true);

		} else {
			ViewGroup parent = (ViewGroup) mContentView.getParent();
			if (parent != null) {
				parent.removeView(mContentView);
			}
		}
		return mContentView;
	}

	private void initView() {
		mTopbarView = (TopbarView) mContentView.findViewById(R.id.topbar);
		mTopbarView.setCenterText("行情信息");
		mTopbarView.setLeftView(false, false);
		mTopbarView.setRightVisible(false);

		mShucai = (TextView) mContentView.findViewById(R.id.tv_shucai);
		mShuiguo = (TextView) mContentView.findViewById(R.id.tv_shuiguo);
		mQita = (TextView) mContentView.findViewById(R.id.tv_qita);
		mChandi = (TextView) mContentView.findViewById(R.id.tv_chandi);
		mShichang = (TextView) mContentView.findViewById(R.id.tv_shichang);
		mListView = (XListView) mContentView.findViewById(R.id.listview);

	}

	private void setUpView() {

		mShucai.setOnClickListener(this);
		mShuiguo.setOnClickListener(this);
		mQita.setOnClickListener(this);
		mChandi.setOnClickListener(this);
		mShichang.setOnClickListener(this);

		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
		mListView.setXListViewListener(this);
	}

	private void requestData(final boolean isLoading) {
		String action;
		if (isLoading) {
			((BaseActivity) getActivity()).startLoadingDialog();
			cursor = "0";
			action = "1";
		} else {
			action = "2";
		}

		RequestService.getInstance().marketPrice(getActivity(), type, action, cursor, offset, addressCode, levelType,
				bigName, PriceEntity.class, new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						((BaseActivity) getActivity()).dismissLoadingDialog();
						if (resultData.isOk()) {
							PriceEntity entity = (PriceEntity) resultData;
							if (entity.getData() != null && entity.getData().getList() != null
									&& entity.getData().getList().size() > 0) {
								if (isLoading) {
									list = entity.getData().getList();
									marketPriceAdapter = new MarketPriceAdapter(getActivity(), list, false);
									mListView.setAdapter(marketPriceAdapter);

									mListView.setPullLoadEnable(true);

								} else {
									list.addAll(entity.getData().getList());
									marketPriceAdapter.setData(list);
								}
								MarketPriceFragment.this.cursor = list.get(list.size() - 1).getInsertTime();
							} else {
								if (isLoading) {
									list = new ArrayList<>();
									marketPriceAdapter = new MarketPriceAdapter(getActivity(), list, false);
									mListView.setAdapter(marketPriceAdapter);
								}
								mListView.setPullLoadEnable(false);
								mListView.endLoadingMore("没有更多了");
							}
						} else {
							((BaseActivity) getActivity()).showToast(resultData.getMsg());
						}
						onLoad();
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						((BaseActivity) getActivity()).dismissLoadingDialog();
						((BaseActivity) getActivity()).showToast(msg);
						onLoad();
					}
				});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_shucai:
			bigName = "蔬菜";
			changeState(R.id.tv_shucai);
			break;
		case R.id.tv_shuiguo:
			bigName = "水果";
			changeState(R.id.tv_shuiguo);
			break;
		case R.id.tv_qita:
			bigName = "其它";
			changeState(R.id.tv_qita);
			break;
		case R.id.tv_chandi:
			selectCity();
			break;
		case R.id.tv_shichang:
			selectMarket();
			break;
		}
	}

	/**
	 * 改变当前选中的状态
	 */
	public void changeState(int id) {
		if (checkedId == id) {
			bigName = null;
			checkedId = -1;
			((TextView) mContentView.findViewById(id)).setTextColor(Color.parseColor("#ffffff"));
		} else {
			checkedId = id;
			mShucai.setTextColor(Color.parseColor("#ffffff"));
			mShuiguo.setTextColor(Color.parseColor("#ffffff"));
			mQita.setTextColor(Color.parseColor("#ffffff"));
			((TextView) mContentView.findViewById(id)).setTextColor(Color.parseColor("#ffff00"));
		}
		requestData(true);
	}

	@Override
	public void onRefresh() {
		requestData(true);
	}

	@Override
	public void onLoadMore() {
		requestData(false);
	}

	/**
	 * 选择 市场
	 */
	private void selectMarket() {
		if (cascadingMenuPopWindowMarket == null) {
			// 向三级menu添加地区数据
			cascadingMenuPopWindowMarket = new CascadingMenuPopWindow(getActivity(),false);
			cascadingMenuPopWindowMarket.setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {

				@Override
				public void getValue(Area city, String fullname) {
					marketCity = CityinfoUtil.convert(city);
					mShichang.setText(fullname);
					addressCode = CityinfoUtil.convert(city).getId();
					type = "1";
					levelType = city.getLevelType();
					requestData(true);
				}

			});
			cascadingMenuPopWindowMarket.showAsDropDown(mShichang, 5, 5);
		} else if (cascadingMenuPopWindowMarket != null && cascadingMenuPopWindowMarket.isShowing()) {
			cascadingMenuPopWindowMarket.dismiss();
		} else {
			cascadingMenuPopWindowMarket.showAsDropDown(mShichang, 5, 5);
		}
	}

	/**
	 * 选择 城市
	 */
	private void selectCity() {
		if (cascadingMenuPopWindowCity == null) {
			// 向三级menu添加地区数据
			cascadingMenuPopWindowCity = new CascadingMenuPopWindow(getActivity());
			cascadingMenuPopWindowCity.setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {

				@Override
				public void getValue(Area city, String fullname) {
					mChandi.setText(fullname);
					if(city.getAreaId()!=null){
						marketCity = CityinfoUtil.convert(city);
						addressCode = CityinfoUtil.convert(city).getId();
						type = "2";
						levelType = city.getLevelType();
					}else{
						addressCode = null;
						type = null;
						levelType = null;
					}
					requestData(true);
				}

			});
			cascadingMenuPopWindowCity.showAsDropDown(mShichang, 5, 5);
		} else if (cascadingMenuPopWindowCity != null && cascadingMenuPopWindowCity.isShowing()) {
			cascadingMenuPopWindowCity.dismiss();
		} else {
			cascadingMenuPopWindowCity.showAsDropDown(mShichang, 5, 5);
		}
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
	}
//
//	/**
//	 * 选完城市 选市场
//	 */
//	private void selectMarket() {
//		if (marketProvince == null && marketCity == null) {
//			selectMarketCity(false);
//		}
//		Intent intent = new Intent(getActivity(), SelectMarketActivity.class);
//		intent.putExtra(ExtraName.proid, marketProvince.getCitycode());
//		intent.putExtra(ExtraName.citycode, marketCity.getCitycode());
//		startActivityForResult(intent, 4);
//	}

	/**
	 * 得到 选择 市场的 返回信息
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == getActivity().RESULT_OK) {
			selectMarket = (Market) data.getSerializableExtra(ExtraName.market);
			// mPifashichangEdit.setText(selectMarket.getName());
			mShichang.setText(selectMarket.getName());
			type = "1";
			levelType = null;
			requestData(true);
		}
	}
}
